//
//  ItemManager.m
//  SAYAKA_Table
//
//  Created by numanuma08 on 2013/07/21.
//  Copyright (c) 2013年 勘米良. All rights reserved.
//

#import "ItemManager.h"
#import "NSArray+mapUsingBlock.h"

@implementation ItemManager
static NSString* const kENTITY = @"Item";

+ (NSString*)entity
{
    return kENTITY;
}

+ (NSArray*)allRecord:(NSManagedObjectContext*)managedobjectContext
{
    NSEntityDescription* entity = [NSEntityDescription entityForName:kENTITY inManagedObjectContext:managedobjectContext];
    
    NSFetchRequest* fetchRequest = [[NSFetchRequest alloc]init];
    fetchRequest.entity = entity;
    
    NSSortDescriptor* sortDescription = [[NSSortDescriptor alloc]initWithKey:@"order_number" ascending:YES];
    fetchRequest.sortDescriptors = @[sortDescription];
    
    NSArray* fetchResult = [managedobjectContext executeFetchRequest:fetchRequest error:nil];
    NSArray* categoris = [fetchResult mapUsingArray:^(id object){ return (Item*)object;}];
    
    return categoris;
}

+ (NSArray*)record:(NSManagedObjectContext*)managedobjectContext byCategory:(Category *)category
{
    NSEntityDescription* entity = [NSEntityDescription entityForName:kENTITY inManagedObjectContext:managedobjectContext];
    
    NSFetchRequest* fetchRequest = [[NSFetchRequest alloc]init];
    fetchRequest.entity = entity;
    
    NSSortDescriptor* sortDescription = [[NSSortDescriptor alloc]initWithKey:@"order_number" ascending:YES];
    fetchRequest.sortDescriptors = @[sortDescription];
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"category1 == %@ || category2 == %@ || category3 == %@", category, category, category];
    NSArray *predicates = [NSArray arrayWithObjects:pred, nil];
    NSPredicate *compound = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
    [fetchRequest setPredicate:compound];
    
    NSArray* fetchResult = [managedobjectContext executeFetchRequest:fetchRequest error:nil];
    NSArray* categoris = [fetchResult mapUsingArray:^(id object){ return (Item*)object;}];
    
    return categoris;
}

+ (Item*)newRecord:(NSManagedObjectContext *)manageobjectContext
{
    NSInteger count = [ItemManager allRecord:manageobjectContext].count - 1;
    
    Item* entity = (Item*)[NSEntityDescription insertNewObjectForEntityForName:kENTITY inManagedObjectContext:manageobjectContext];
    entity.order_number = [NSNumber numberWithInteger:count];
    
    return entity;
}
@end
